package com.shitou.shitoumember.service.impl;

import com.shitou.shitoucommons.exception.RRException;
import com.shitou.shitoucommons.utils.RespBean;
import com.shitou.shitoumember.entity.MemberStatisticsInfoEntity;
import com.shitou.shitoumember.feign.SpuFeign;
import com.shitou.shitoumember.service.MemberStatisticsInfoService;
import com.shitou.shitoumember.vo.CollectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shitou.shitoucommons.utils.PageUtils;
import com.shitou.shitoucommons.utils.Query;

import com.shitou.shitoumember.dao.MemberCollectSpuDao;
import com.shitou.shitoumember.entity.MemberCollectSpuEntity;
import com.shitou.shitoumember.service.MemberCollectSpuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional
@Service("memberCollectSpuService")
public class MemberCollectSpuServiceImpl extends ServiceImpl<MemberCollectSpuDao, MemberCollectSpuEntity> implements MemberCollectSpuService {


    @Autowired
    private MemberStatisticsInfoService statisticsInfoService;

    @Resource
    private SpuFeign spuFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberCollectSpuEntity> page = this.page(
                new Query<MemberCollectSpuEntity>().getPage(params),
                new QueryWrapper<MemberCollectSpuEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 创建收藏的商品s
     * @param vo
     * @see CollectVo
     * @return
     */
    @Override
    public RespBean crateCollect(CollectVo vo) {

        // 判断该商品是不是自己发布的，不能自己收藏自己的商品
        checkPublisherIsMyself(vo.getMemberId(), vo.getSpuId());

        MemberCollectSpuEntity umsMemberCollectSpu = this.getOne(new QueryWrapper<MemberCollectSpuEntity>().eq("spu_id", vo.getSpuId())
                .eq("member_id", vo.getMemberId()));

        if ( umsMemberCollectSpu != null ) {
            umsMemberCollectSpu.setCreateTime(new Date());
            umsMemberCollectSpu.setBeforePrice(vo.getPrice());
            umsMemberCollectSpu.setSpuName(vo.getSpuName());
            umsMemberCollectSpu.setSpuImg(vo.getSpuImg());

            this.updateById(umsMemberCollectSpu);
            return RespBean.success();
        }

        MemberCollectSpuEntity memberCollectSpu = new MemberCollectSpuEntity();
        memberCollectSpu.setMemberId(vo.getMemberId());
        memberCollectSpu.setSpuId(vo.getSpuId());
        memberCollectSpu.setBeforePrice(vo.getPrice());

        memberCollectSpu.setSpuName(vo.getSpuName());
        memberCollectSpu.setSpuImg(vo.getSpuImg());

        memberCollectSpu.setCreateTime(new Date());
        this.save(memberCollectSpu);
        addCollectCount(vo.getMemberId());
        return RespBean.success();
    }

    /**
     * 删除，真实删除
     * @param memberId 用户id
     * @param id 购物车id
     * @return
     */
    @Override
    public RespBean deleteCollect(long memberId, long id) {
        this.remove(new QueryWrapper<MemberCollectSpuEntity>().eq("member_id", memberId).eq("id", id));
        return RespBean.success();
    }


    /**
     * 批量删除
     * @param memberId
     * @param idS
     * @return
     */
    @Override
    public RespBean deleteBatchCollect(long memberId, long[] idS) {
        List<MemberCollectSpuEntity> list = this.list(new QueryWrapper<MemberCollectSpuEntity>().eq("member_id", memberId));
        List<Long> deleteIds = new ArrayList<>();
        for (long id : idS) {
            MemberCollectSpuEntity collectSpuEntity = list.stream()
                    .filter(entity -> entity.getId().equals(id))
                    .findFirst()
                    .orElse(null);
            if ( collectSpuEntity != null ){
                deleteIds.add(id);
            }
        }
        if ( deleteIds.size() == 0 ){
            throw new RRException("批量删除失败");
        }
        this.removeByIds(deleteIds);
        return RespBean.success();
    }


    /**
     * 获取当前用户的所有收藏的商品
     * @param memberId
     * @return
     */
    @Override
    public RespBean getMemberCollect(long memberId) {
        List<MemberCollectSpuEntity> list = this.list(new QueryWrapper<MemberCollectSpuEntity>().eq("member_id", memberId));

        return RespBean.success().put("data", list);
    }


    /**
     *
     */
    public void addCollectCount(long memberId){
        MemberStatisticsInfoEntity memberStatisticsInfo = statisticsInfoService.getOne(new QueryWrapper<MemberStatisticsInfoEntity>().eq("member_id", memberId));
        if ( memberStatisticsInfo == null ){
            throw new RRException("获取用户信息失败");
        }
        memberStatisticsInfo.setCollectProductCount(memberStatisticsInfo.getCollectProductCount() + 1);
        statisticsInfoService.updateById(memberStatisticsInfo);
    }


    /**
     * 检查该商品是否是自己的商品
     * @param memberId
     * @param spuId
     * @return
     */
    public void checkPublisherIsMyself(Long memberId, Long spuId){
        String data = null;
        try {
            RespBean respBean = spuFeign.checkPublisherIsMyself(memberId, spuId);
            if ( respBean == null ){
                throw new RRException("收藏商品失败，请联系管理员");
            }
            data = (String) respBean.get("data");
        } catch (Exception e){
            throw new RRException("收藏商品失败，请联系管理员");
        }
        boolean isMyselfProduct = Boolean.parseBoolean(data);
        if ( isMyselfProduct ){
            throw new RRException("不能收藏自己的商品哦");
        }
    }
}
